package com.smile.cn.entity.config;

import java.io.InputStream;
import java.util.HashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import com.smile.cn.entity.EMailServer;
import com.smile.cn.entity.EMailServers;

public class EMailConfig {

	private static HashMap<String, EMailServer> servers = null;

	public static EMailServer getEMailServerByUser(String user)
			throws Exception {
		if (servers == null) {
			try {
				init();
			} catch (Exception e) {
				throw new Exception("fetch xml data failed", e);
			}
		}
		int idx = user.indexOf("@");
		String mailname = user;
		if (idx > 0) {
			mailname = user.substring(idx + 1);
		}
		if (servers.containsKey(mailname)) {
			return servers.get(mailname);
		}
		return null;
	}

	/**
	 * fetch isp info from xml
	 * @param filename
	 * @return InputStream
	 * @throws Exception
	 */
	private static InputStream getConfig(String filename) throws Exception {
		InputStream in = null;
		try {
			ClassLoader classloader = Thread.currentThread()
					.getContextClassLoader();
			in = classloader.getResourceAsStream("config/" + filename);
		} catch (Exception ex) {
			throw new Exception("get properties file failed", ex);
		}
		return in;
	}

	private static void init() throws Exception {
		try {
			if (servers != null) {
				return;
			}
			servers = new HashMap<String, EMailServer>();
			InputStream in = getConfig("email_config.xml");
			JAXBContext jc = JAXBContext
					.newInstance(new Class[] { EMailServers.class });
			Unmarshaller u = jc.createUnmarshaller();
			EMailServers _servers = (EMailServers) u.unmarshal(in);
			for (EMailServer serv : _servers.getEMailServer()) {
				String mailname = serv.getMailname();
				servers.put(mailname, serv);
			}
		} catch (Exception e) {
			throw new Exception("get the stream of email_config.xml failed", e);
		}
	}
}
